<template>
  <div class="container">
    <button @click="add">在任意位置添加一项</button>
    <button @click="remove">在任意位置移除一项</button>
    <button @click="doShuffle">重新排序</button>
    <TransitionGroup name="list" tag="ul">
      <li v-for="item in items" :key="item">{{ item }}</li>
    </TransitionGroup>
  </div>
</template>

<script setup>
// 这种方式有问题
import { shuffle as _shuffle } from 'lodash-es'
import { reactive } from 'vue'
const getInitialItems = () => [
  1, 2, 3, 4, 5
]
let items = reactive(getInitialItems())
console.log(items)
let initData = items.at(-1) + 1


function add() {
  if (items.length) {
    const index = Math.floor(Math.random() * items.length)
    items.splice(index, 0, (initData++))
    return
  }
  items.splice(0, 0, 1)
}
function remove() {
  if (items.length) {
    const index = Math.floor(Math.random() * items.length)
    items.splice(index, 1)
    return
  }
  alert('没有元素可以删除啦！')
}
function doShuffle() {
  items = _shuffle(items)
  console.log(items) // 这个地方的items丢失了响应性
}
</script>

<style scoped>
/* 对移动中的元素应用到过渡 */
.list-move,
.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease;
}
.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

/* 确保将离开的元素从布局流中删除，以便能够正确地计算移动的动画 */
.list-leave-active {
  position: absolute;
}

.container {
  overflow: hidden;
}
</style>